const cheerio = require('cheerio')
const { request ,request2} = require('./request')
const tag = '删帖' // 帖子
const { getTBS } = require('./utils')

let requestInterval = 350
let tbs = ''

// 删除多个
async function deleteMultiple(config) {

  let { start, end, interval } = config
  requestInterval = interval || 350
  if(!start || !end){
    if(start){
      end = start
    }else if(end){
      start = end
    }else{
      console.log(`${tag}: 请设置开始和结束页 `)
      return false
    }
  }else if(start > end){
    start = end
  }

  const list = await getMultiplePage(start,end)
  const len = list.length
  if (len === 0) {
    console.log(`${tag}: 完成`)
    return false
  }

  for (let index = len - 1; index >= 0; index--) {
    console.log(`${tag}> ${list[index].tieba} : ${list[index].title}`)
    // const status = await deleteOne(list[index])
        const status = true
    if(status !== true && status && status.err_code == 220034){
      console.log(`${tag}: >>> 删除限制 <<< , 请明天再尝试`)
      return false
    }
  }
  console.log(`${tag}: 完成`)
}

// 删除一个
async function deleteOne(params) {

  tbs = await getTBS()
  if(!tbs){
    console.log(`${tag}: 请重新登陆，并设置cookie! `)
    return false
  }

  const fd = new URLSearchParams()
  Object.keys(params).forEach(key => {
    fd.append(key, params[key])
  })
  fd.append('tbs',tbs)

  const url = 'https://tieba.baidu.com/f/commit/post/delete'
  const response = await request(url, {
    method: 'POST',
    body: fd
  })
  const data = await response.json()

  return new Promise(resolve => {
    setTimeout(() => {
      if (data.err_code === 0) {
        console.log(`${tag}: 删除成功`)
        resolve(true)
      } else {
        console.log(`${tag}: 删除错误:`, JSON.stringify(data))
        resolve(data)
      }
    }, requestInterval)
  })
}

// 获取多页
async function getMultiplePage(start, end) {
  console.log(`${tag}: 获得, 页面:${start}->${end}`)
  const data = []
  for (let page = end; page >= start; page--) {
    let list = await getOnePage(page)
    data.push(...list)
  }
  console.log(`${tag}: 获得总数: ${data.length}`)
  return data
}

// 获取一页
async function getOnePage(page) {
  const url = `https://tieba.baidu.com/i/i/my_tie?&pn=${page}`
  const response = await request(url)
  const data = await response.text()
  const $ = cheerio.load(data)

  // const list = $('a.thread_title').map((index, el) => {
  //   const href = $(el).attr('href')
  //   let tid = href.match(/\/p\/([0-9]+)/) 
  //   tid = tid && tid[1] || null
  //   let pid = href.match(/pid=([0-9]+)/)
  //   pid = pid && pid[1] || null

  //   return { tid, pid }
  // });

    const list = $('div.wrap_container').map((index, el) => {
    const href = $(el).find('a.thread_title').attr('href')
    let tid = href.match(/\/p\/([0-9]+)/) 
    tid = tid && tid[1] || null
    let pid = href.match(/pid=([0-9]+)/)
    pid = pid && pid[1] || null
    let tieba = $(el).find('td.nowrap').find('a').text()
    let title = $(el).find('a.thread_title').text()
    return { tid, pid,tieba,title}
  });

  return new Promise(resolve=>{
    setTimeout(()=>{
      console.log(`${tag}: 获得, 页面:${page}, 数量:${list.length}`)
      resolve(list)
    },requestInterval)
  })
}

module.exports.deletePosts = deleteMultiple